package com.by_man.presenter.module_health_consultant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.PostJsonArrayRequest;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;

/**
 * Created by man on 2017-02-23.
 */
public class HealthConsultantFragment extends Fragment {
    private RequestQueue rQueue;
    private ImageLoader imageLoader;
    private Views views;
    private Handler handler;

    private final static int GET_DATA_SUCCESS = 0x1;
    private final static int GET_DATA_FAIL = 0x2;
    private final static int GET_ONE_DATA_SUCCESS = 0x4;
    private final static int GET_ONE_DATA_FAIL = 0x8;


    // 存储医生信息的列表
    List<Map<String, Object>> docInfos = new ArrayList<Map<String, Object>>();

    final ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

    private String userid;
    //private String docName;
    private boolean isFull = false;

    @Override   //绑定布局
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_health_consultant, container, false);
        views = new Views();
        initView(view);
        rQueue = SharedApplication.getrQueue(getActivity().getApplication());
        imageLoader = SharedApplication.getImageLoader(getActivity().getApplication());
        rQueue.start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case GET_DATA_SUCCESS:
                        getDataSuccess(msg.getData());
                        break;
                    case GET_DATA_FAIL:
                        getDataFail();
                        break;
                    case GET_ONE_DATA_SUCCESS:
                        getOneDataSuccess(msg.getData());
                        break;
                    case GET_ONE_DATA_FAIL:
                        getOneDataFail(msg.getData());
                        break;
                    default:
                        break;
                }
            }
        };

        // 进行网络请求
        getDataByNet();
        return view;
    }

    private class Views {
        TextView textView;
        ListView listView;
    }

    private void initView(View view) {
        //  获取所有的ui组件
        views.textView = (TextView) view.findViewById(R.id.text_view);
        views.listView = (ListView) view.findViewById(R.id.list_doc);

        // 为组件注册监听
        views.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                getOneDataByNet(i);
            }
        });
    }

    // 进行网络请求数据
    private void getDataByNet() {
        // 进行网络请求数据
        HashMap<String, String> params = new HashMap<>();
        params.put("token", UserInfos.token);
        PostStringRequest postStringRequest = new PostStringRequest(Request.Method.POST, IpAddress.All_Doctor, params,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.d("Response", s);
                        // 通知handler执行相应操作
                        Message msg = handler.obtainMessage();
                        msg.what = GET_DATA_SUCCESS;
                        Bundle bundle = new Bundle();
                        bundle.putString("All_Doctor", s);
                        msg.setData(bundle);
                        msg.sendToTarget();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("Error", volleyError.getMessage(), volleyError);
                        Message msg = handler.obtainMessage();
                        msg.what = GET_DATA_FAIL;
                        msg.sendToTarget();
                    }
                });
        rQueue.add(postStringRequest);
    }

    // 进行网络请求，请求一个医生信息
    private void getOneDataByNet(final int i) {

        HashMap<String, String> paramsPost = new HashMap<String, String>();
        if (isFull) {
            // 获取医生详细信息
            paramsPost.put("token", UserInfos.token);
            paramsPost.put("arg",userid);
            final int position = i;
            PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Doctor_Infos, paramsPost,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Message msg = handler.obtainMessage();
                            msg.what = GET_ONE_DATA_SUCCESS;
                            Bundle bundle = new Bundle();
                            bundle.putString("One_Doctor", response);
                            bundle.putBoolean("Ischosed", true);
                            bundle.putString("Name",(String)docInfos.get(position).get("13"));
                            msg.setData(bundle);
                            msg.sendToTarget();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("HealthConsultantError",volleyError.getMessage(),volleyError);
                            Message msg = handler.obtainMessage();
                            msg.what = GET_ONE_DATA_FAIL;
                            Bundle bundle = new Bundle();
                            bundle.putInt("Postion", i);
                            msg.setData(bundle);
                            msg.sendToTarget();
                        }
                    });
            rQueue.add(stringRequest);
        } else {
            paramsPost.put("token", UserInfos.token);
            final String id = (String)docInfos.get(i).get("userid");
            final String name = (String) docInfos.get(i).get("13");
            paramsPost.put("arg", id);
            PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST, IpAddress.Doctor_Infos, paramsPost,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Message msg = handler.obtainMessage();
                            msg.what = GET_ONE_DATA_SUCCESS;
                            Bundle bundle = new Bundle();
                            bundle.putString("One_Doctor", response);
                            bundle.putBoolean("Ischosed", false);
                            bundle.putString("Name",name);
                            msg.setData(bundle);
                            msg.sendToTarget();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("HealthConsultantError",volleyError.getMessage(),volleyError);
                            Message msg = handler.obtainMessage();
                            msg.what = GET_ONE_DATA_FAIL;
                            Bundle bundle = new Bundle();
                            bundle.putInt("Postion", i);
                            msg.setData(bundle);
                            msg.sendToTarget();
                        }
                    });
            rQueue.add(stringRequest);
        }
    }


    private class ListViewAdapter extends BaseAdapter {
        @Override
        public int getCount()
        {
            return docInfos.size();
        }

        @Override
        public Object getItem(int position)
        {
            return docInfos.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            if(null == convertView) {
                convertView = View.inflate(getActivity(), R.layout.health_consultant_listview_item, null);
            }

            TextView nameView= (TextView) convertView.findViewById(R.id.docname);
            TextView jobView= (TextView) convertView.findViewById(R.id.job);
            ImageView imageview = (ImageView)convertView.findViewById(R.id.path);
            if(!docInfos.get(position).get("18").equals("null")) {
                String url = IpAddress.Load_Image + docInfos.get(position).get("18");
                //rQueue.add(SharedApplication.imageRequest(url, imageview, getActivity()));
                ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageview,R.drawable.no,R.drawable.no);
                imageLoader.get(url, listener);
            }

            //13医生姓名；14医生职称；18医生图片
            nameView.setText((String) docInfos.get(position).get("13"));
            jobView.setText((String) docInfos.get(position).get("14"));
            return convertView;
        }
    }

    // 请求数据成功执行
    private void getDataSuccess(Bundle bundle) {
        String str = bundle.getString("All_Doctor", "");
        if (null != str && str.length() != 0) {
            try {
                JSONArray jsonArray = new JSONArray(str);
                JSONObject isSelect = (JSONObject) jsonArray.get(0);
                if (isSelect.getBoolean("isFull")) {
                    isFull = true;
                    JSONObject infoDoc = (JSONObject) jsonArray.get(1);
                    //13医生姓名；14医生职称；18医生图片
                    final HashMap<String, Object> hashdoc = new HashMap<String, Object>();
                    hashdoc.put("13", infoDoc.getString("value"));
                    hashdoc.put("14", infoDoc.getString("job"));
                    hashdoc.put("18", infoDoc.getString("path"));
                    userid = infoDoc.getString("userid");
                    docInfos.clear();
                    docInfos.add(hashdoc);
                    views.textView.setText("你的顾问");
                    views.listView.setAdapter(new ListViewAdapter());
                } else {
                    isFull = false;
                    //没有选择顾问，开始申请医院名称、地址、医生等
                    Map<String, Object> test1 = new HashMap<String, Object>();
                    JSONObject temp1 = (JSONObject) jsonArray.get(1);
                    String users_id = temp1.getString("users_id");
                    for (int j = 1; j < jsonArray.length(); j++) {
                        JSONObject temp2 = (JSONObject) jsonArray.get(j);
                        final String users_id2 = temp2.getString("users_id");
                        if (users_id.equals(users_id2)) {
                            final String list_id = temp2.getString("list_id");
                            final String value = temp2.getString("value");
                            test1.put(list_id, value);
                        } else {
                            test1.put("userid", users_id);
                            docInfos.add(test1);
                            users_id = users_id2;
                            test1 = new HashMap<String, Object>();
                        }
                    }
                    views.listView.setAdapter(new ListViewAdapter());

                }
            } catch (JSONException je) {
                je.printStackTrace();
            }
        }
    }

    // 请求数据失败执行
    private void getDataFail() {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提醒")
                .setMessage("请求服务器失败，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       getDataByNet();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    // 请求单个医生信息成功
    private void getOneDataSuccess(Bundle bundle) {
        String response = bundle.getString("One_Doctor", "");
        String name = bundle.getString("Name","");
        boolean ischosed = bundle.getBoolean("Ischosed", false);
        if (response != null && response.length() != 0) {
            Intent intent = new Intent(getActivity(), DoctorInfosActivity.class);
            intent.putExtra("jsonString", response);
            intent.putExtra("ischosed", ischosed);
            intent.putExtra("name", name);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }

    // 请求单个医生信息失败
    private void getOneDataFail(final Bundle bundle) {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提醒")
                .setMessage("请求医生信息失败，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        int position = bundle.getInt("Position",0);
                        getOneDataByNet(position);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    // 不知能否解决内存泄露
    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

}
